1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import com.google.common.annotations.GwtCompatible;
20 import com.google.common.collect.testing.google.TestStringBiMapGenerator;
21
22 import junit.framework.TestCase;
23
24 import java.util.Iterator;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Set;
28
29
30
31
32
33
34 @GwtCompatible(emulated = true)
35 public class HashBiMapTest extends TestCase {
36
37 public static final class HashBiMapGenerator extends TestStringBiMapGenerator {
38 @Override
39 protected BiMap<String, String> create(Entry<String, String>[] entries) {
40 BiMap<String, String> result = HashBiMap.create();
41 for (Entry<String, String> entry : entries) {
42 result.put(entry.getKey(), entry.getValue());
43 }
44 return result;
45 }
46 }
47
48 public void testMapConstructor() {
49
50 Map<String, String> map = ImmutableMap.of(
51 "canada", "dollar",
52 "chile", "peso",
53 "switzerland", "franc");
54 HashBiMap<String, String> bimap = HashBiMap.create(map);
55 assertEquals("dollar", bimap.get("canada"));
56 assertEquals("canada", bimap.inverse().get("dollar"));
57 }
58
59 private static final int N = 1000;
60
61 public void testBashIt() throws Exception {
62 BiMap<Integer, Integer> bimap = HashBiMap.create(N);
63 BiMap<Integer, Integer> inverse = bimap.inverse();
64
65 for (int i = 0; i < N; i++) {
66 assertNull(bimap.put(2 * i, 2 * i + 1));
67 }
68 for (int i = 0; i < N; i++) {
69 assertEquals(2 * i + 1, (int) bimap.get(2 * i));
70 }
71 for (int i = 0; i < N; i++) {
72 assertEquals(2 * i, (int) inverse.get(2 * i + 1));
73 }
74 for (int i = 0; i < N; i++) {
75 int oldValue = bimap.get(2 * i);
76 assertEquals(2 * i + 1, (int) bimap.put(2 * i, oldValue - 2));
77 }
78 for (int i = 0; i < N; i++) {
79 assertEquals(2 * i - 1, (int) bimap.get(2 * i));
80 }
81 for (int i = 0; i < N; i++) {
82 assertEquals(2 * i, (int) inverse.get(2 * i - 1));
83 }
84 Set<Entry<Integer, Integer>> entries = bimap.entrySet();
85 for (Entry<Integer, Integer> entry : entries) {
86 entry.setValue(entry.getValue() + 2 * N);
87 }
88 for (int i = 0; i < N; i++) {
89 assertEquals(2 * N + 2 * i - 1, (int) bimap.get(2 * i));
90 }
91 }
92
93 public void testBiMapEntrySetIteratorRemove() {
94 BiMap<Integer, String> map = HashBiMap.create();
95 map.put(1, "one");
96 Set<Map.Entry<Integer, String>> entries = map.entrySet();
97 Iterator<Map.Entry<Integer, String>> iterator = entries.iterator();
98 Map.Entry<Integer, String> entry = iterator.next();
99 entry.setValue("two");
100 assertEquals("two", map.get(1));
101 assertEquals(Integer.valueOf(1), map.inverse().get("two"));
102 iterator.remove();
103 assertTrue(map.isEmpty());
104 }
105 }
106